<template>
  <el-form :model="userPwd" status-icon :rules="rules2" ref="userPwd" label-width="100px" class="demo-ruleForm">
    <el-form-item label="旧密码" prop="oldpassword">
      <el-input type="password" v-model.number="userPwd.oldpassword"></el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="newpassword">
      <el-input type="password" v-model="userPwd.newpassword" auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="checkpassword">
      <el-input type="password" v-model="userPwd.checkpassword" auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('userPwd')">提交</el-button>
      <el-button @click="resetForm('userPwd')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: 'PasswordCenter',
  data () {
    var checkOld = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('旧密码不能为空'))
      } else {
        callback()
      }
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.userPwd.newpassword !== '') {
          this.$refs.userPwd.validateField('checkpassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.userPwd.newpassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      userPwd: {
        newpassword: '',
        checkpassword: '',
        oldpassword: ''
      },
      rules2: {
        oldpassword: [
          { validator: checkOld, trigger: 'blur' }
        ],
        newpassword: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkpassword: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm  (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$customerAPI.user_change_pwd({
            'oldpassword': this.userPwd.oldpassword,
            'newpassword': this.userPwd.newpassword
          }).then((params) => {
            this.$message({ type: 'success', message: '修改成功！' })
            this.resetForm(formName)
          })
        } else {
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>

</style>
